<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="600">
      <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="state.ruleForm.name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="state.ruleForm.description" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-tree
            ref="treeRef"
            :data="state.treeData"
            :props="{
              label: 'name',
            }"
            :default-expanded-keys="['ALL']"
            check-strictly
            node-key="key"
            show-checkbox
            style="height: 400px;overflow-y: auto;width: 100%;"
            @check="onCheckChange"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="state.submit.loading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="roleDialog">
import { nextTick, reactive, ref } from 'vue';
import { DialogType } from '/@/constants/dialog-type';
import { createRole, updateRole } from '/@/api/role';
import { ElMessage } from 'element-plus';
import { assginDefault } from '/@/utils/assign-default';
import { Role } from '/@/models';
import { readAllPermission } from '/@/api/permission';
import { toTree } from '/@/utils/to-tree';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const formRef = ref();
const treeRef = ref();
const state = reactive({
  id: '',
  ruleForm: {
    description: '',
    name: '',
    permissions: [],
  },
  rules: {
    name: [{ required: true, message: '不能为空' }],
    permissions: { required: true, message: '权限不能为空' },
  },
  roleList: [],
  submit: {
    loading: false,
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
  },
  authList: [],
  treeData: [],
});

// 打开弹窗
const openDialog = (type: string, row?: Role) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  nextTick(() => {
    if (type === DialogType.EDIT) {
      state.id = row.id;
      assginDefault(state.ruleForm, row);

      const list = row.permissions?.split(',') || [];
      treeRef.value.setCheckedKeys(list);
      state.dialog.title = '修改角色';
    } else {
      state.id = '';
      state.dialog.title = '新增角色';
      treeRef.value.setCheckedKeys([]);
      formRef.value?.resetFields();
    }
  });

  if (state.treeData.length === 0) {
    getPermissionTree();
  }
};

const getPermissionTree = async () => {
  const { data } = await readAllPermission();
  state.authList = data;
  state.treeData = toTree(data);
};

const onCheckChange = (_, checkParams: any) => {
  state.ruleForm.permissions = checkParams.checkedKeys;
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = async () => {
  await formRef.value.validate();
  try {
    state.submit.loading = true;
    let permissions = state.ruleForm.permissions;
    if (typeof permissions === 'string') {
      permissions = (permissions as string).split(',');
    }
    const index = permissions.indexOf('ALL');

    if (index > -1) {
      permissions.splice(index, 1);
    }

    const data = { ...state.ruleForm, permissions };

    if (state.dialog.type === DialogType.EDIT) {
      await updateRole(state.id, data);
    } else {
      await createRole(data);
    }
    ElMessage.success('保存成功');
    closeDialog();
    emit('refresh');
  } catch (err) {
    console.log(err);
  }

  state.submit.loading = false;
};

// 暴露变量
defineExpose({
  openDialog,
  closeDialog,
});
</script>
